import React, { PureComponent } from 'react';
import {
  Icon,
  Button,
  Upload,
  Progress,
  message
} from 'antd';
import {connect} from 'dva';
import G from '../../utils/g';

@connect(state => ({
  addGoods: state.addGoods,
}))
export default class UploadVideo extends PureComponent {
  state = {
    showProgress : false,
    percent : 0,
    fileList : this.props.fileList || [
    ]
  };

  componentWillReceiveProps(props,state){
    if(props.fileList.length != this.state.fileList.length){
      this.setState({
        fileList : props.fileList
      });
    }
  };

  beforeUpload = (file)=>{
    // const uptoken = this.props.uptoken;
    let fileList = [...this.state.fileList];
    // const {onChange} = this.prop;

    this.setState({
      showProgress : true
    });
    const formData = new FormData();
    formData.append('files', file);
    const {dispatch} = this.props;
    dispatch({
      type: 'addGoods/uploadVideo',
      payload: formData
    }).then(res=>{
      if(res){
        fileList = [{
                      uid: G.uuid(16),
                      name: file.name,
                      status: 'done',
                      url: res[0]
                    }];
        this.setState({
          fileList,
          showProgress : false
        });
        // typeof onChange == 'function' && onChange(fileList);
        this.props.onChange(fileList);
      }else{
        message.error('上传失败');
        this.setState({
          showProgress : false
        });
      }
    });
    // QiniuUploader({
    //   file ,
    //   putExtra : {
    //     mimeType : ['video/mp4']
    //   },
    //   success : (url)=>{
    //     fileList = [{
    //       uid: G.uuid(16),
    //       name: file.name,
    //       status: 'done',
    //       url: url
    //     }];
    //
    //     this.setState({
    //       fileList,
    //       showProgress : false
    //     });
    //     this.props.onChange(fileList);
    //   },
    //   error : (err)=>{
    //     this.setState({
    //       showProgress : false
    //     });
    //   },
    //   next : (res)=>{
    //     console.log(res);
    //     this.setState({
    //       percent : res.total.percent
    //     });
    //   },
    // });

    return false;
  };

  handleUploadChange = ({fileList})=> {
    this.setState({fileList});
    this.props.onChange(fileList);
  };

  render(){
    const { fileList, percent, showProgress } = this.state;
    return <div>
      {
        fileList.length >= 1 ?
          <div><video src={fileList[0].url} width={320} height={200} controls /></div> :
        null
      }
      <Upload
        accept="video/*"
        action=""
        beforeUpload={this.beforeUpload}
        onChange={this.handleUploadChange}
        fileList = {fileList}
      >
        <Button>
          <Icon type="upload" /> 点击上传
        </Button>
        {
          showProgress ? <Progress percent={percent} size="small" /> : null
        }

      </Upload>
    </div>
  }
}
